# -*- coding: utf-8 -*-
import time

import network

try:
    import ure as re
except ImportError:
    import re

try:
    import usocket as socket
except ImportError:
    import socket

import machine
import ubinascii


class Setnetwork():
    '''配网类'''

    def __init__(self, config):
        self.wificonf = config['wificonf']
        self.equipm = config['equipm']
        self.test_wifi_cs = 0
        if 'statusled' in config['gpio'] and config['gpio']['statusled']!='':
            from statusled import statusled
            ledclass = statusled(config['gpio']['statusled'])
            self.led_kuai_shang = ledclass.kuai_shang
        self.index_html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>请打开微信小程序给设备配网</title></head><body>请打开微信小程序给设备配网</body></html>'

    def test_wifi(self, sta):
        if sta.isconnected():
            self.test_wifi_cs = 0
            return True
        else:
            if self.test_wifi_cs < 15:
                time.sleep(1)
                self.test_wifi_cs += 1
                return self.test_wifi(sta)
            else:
                return False
            return False


    def ConnectWifi(self,request):
        # 取出wifi名字密码
        r = re.search('wifiname=(.*)&wifipass=(.*)&scanssid=(.*)&respiid=(.*) HTTP',request)
        ssid = r.group(1)
        password = r.group(2)
        scanssid = r.group(3)
        respiid = r.group(4)

        # 如果找到中文ssid进行译码
        try:
            r = re.search('(%..)+', ssid)
            cn = r.group(0)
            cn_byte = cn.replace('%', r'\x')
            cn_byte = eval("b"+"\'"+cn_byte+"\'")
            ssid = ssid.replace(cn, cn_byte.decode())
        except Exception:pass

        # 连接wifi
        self.test_wifi_cs = 0
        network.WLAN(network.AP_IF).active(False)
        sta = network.WLAN(network.STA_IF)
        sta.active(False)
        sta.active(True)
        sta.connect(ssid,password)
        if self.test_wifi(sta):
            return True, ssid,password,scanssid,respiid
        else:
            return False, '', '', '', ''

    def enable_ap(self):
        ap = network.WLAN(network.AP_IF)
        ap.active(False)
        ap.active(True)
        ap.config(essid='设备配网',authmode=0)
        return ap

    def led_kuai_shang(self, status):
        pass

    def main(self):
        # 关闭sta模式
        sta = network.WLAN(network.STA_IF)
        sta.active(False)

        self.enable_ap()

        addr = socket.getaddrinfo('192.168.4.1', 80)[0][-1]
        s = socket.socket()
        s.bind(addr)
        s.listen(5)

        print('请打开【自美系统】微信小程序=>进入设备管理=>万能开关=>添加设备')

        self.led_kuai_shang(True)

        while True:
            # 获取request
            cl, addr = s.accept()
            request = cl.recv(1024).decode()
            get = request.split('\n')[0]

            # 屏蔽对favicon.ico的请求
            if 'favicon.ico' in get:
                cl.sendall('HTTP/1.1 404')
                cl.close()
                continue
            else:
                responseHeaders = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"
                cl.send(responseHeaders)

            if 'xiaocx' in get:
                is_conn, ssid, password, scanssid, respiid = self.ConnectWifi(request.split('\n')[0])
                del scanssid
                if is_conn:
                    wri_str = str(ssid)+'\n'+str(password)
                    with open(self.wificonf,'w') as fp:
                        fp.write(wri_str)
                    with open(self.equipm,'w') as fp:
                        fp.write(str(respiid))
                    try:
                        cl.sendall('{"state":"success"}')
                        cl.close()
                    except OSError:pass
                    print('配网成功！设备即将重启后生效。')
                    self.led_kuai_shang(False)
                    machine.reset()
                else:
                    self.enable_ap()
                    try:
                        cl.sendall('{"state":"fail"}')
                        cl.close()
                    except OSError:pass
                    self.led_kuai_shang(True)
                    print('配网失败！请重新操作一次。')
                continue

            if 'deviceid' in get:
                device_name = ubinascii.hexlify(machine.unique_id()).decode()
                cl.sendall(device_name)
                cl.close()
                continue

            if ('index' in get) or (len(get)==15):
                cl.sendall(self.index_html)
                cl.close()
                continue
